package daoImp;

import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import twitter4j.Trend;
import twitter4j.Trends;
import util.DateUtil;
import dao.TrendsDAO;

public class TrendsDAOImp implements TrendsDAO{

	private static TrendsDAOImp uniqueInstance = new TrendsDAOImp();
	private ConnectionPool pool = ConnectionPool.getInstance();
	public static TrendsDAO getInstance() {
		return uniqueInstance;
	}

	private TrendsDAOImp() {
	}
	
	public ArrayList<String> getAllTrends() {
		String sql = null;
		ArrayList<String> trends = new ArrayList<String>();
		try {
			Connection connection;
			try {
				connection = pool.getConnection();
			} catch (Exception e) {
				e.printStackTrace();
				return trends;
			}
			Statement stmt = connection.createStatement();
			sql = "select name from trends;";
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String trend = rs.getString(1);
				trends.add(trend);
			}
			pool.returnConnection(connection);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return trends;
	}

	public ArrayList<String> getTrendsByDate(java.util.Date date) {
		String sql = null;
		ArrayList<String> trends = new ArrayList<String>();
		String dateStr = DateUtil.getDateStr(date);
		
		try {
			Connection connection;
			try {
				connection = pool.getConnection();
			} catch (Exception e) {
				e.printStackTrace();
				return trends;
			}
			Statement stmt = connection.createStatement();
			sql  = "select name from trends where date = '" + dateStr + "';";
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String trend = rs.getString(1);
				trends.add(trend);
			}
			pool.returnConnection(connection);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return trends;
	}
	
	public ArrayList<String> getUsefulTrendsByDate(java.util.Date date) {
		String sql = null;
		ArrayList<String> trends = new ArrayList<String>();
		String dateStr = DateUtil.getDateStr(date);
		
		try {
			Connection connection;
			try {
				connection = pool.getConnection();
			} catch (Exception e) {
				return trends;
			}
			Statement stmt = connection.createStatement();
			sql  = "select name from trends where date = '" + dateStr + "' and avalible = '" + 1 +"';";
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String trend = rs.getString(1);
				trends.add(trend);
			}
			pool.returnConnection(connection);
		} catch (SQLException e) {
		}
		return trends;
	}

}
